import requests
from flask import Blueprint, jsonify, request

# from applications.app.WXBizDataCrypt import WXBizDataCrypt
from applications.models import AppUser
from applications.extensions import db
from applications.common.utils.validate import str_escape

bp = Blueprint('user', __name__, url_prefix='/user')

@bp.post('/login')
def login():
    AppID = "wxf23192318da168c0"
    AppSecret = "3ae6f28b2666adcd14e7b0103306c939"
    wechartUrl = "https://api.weixin.qq.com/sns/jscode2session"

    req_json = request.get_json(force=True)
    code = str_escape(req_json.get('code'))
    nickName = str_escape(req_json.get('nickName'))
    avatarUrl = str_escape(req_json.get('avatarUrl'))

    url = f"{wechartUrl}?appid={AppID}&secret={AppSecret}&js_code={code}&grant_type=authorization_code"
    access_token_openid_dict = requests.get(url).json()
    print(access_token_openid_dict)
    session_key = access_token_openid_dict["session_key"]
    openid = access_token_openid_dict["openid"]
    # 根据openid查询用户信息,判断是否存在用户信息，如果存在，直接登录成功，如果不存在，获取用户手机号

    signature = str_escape(req_json.get('signature'))
    rawData = str_escape(req_json.get('rawData'))
    encryptedData = str_escape(req_json.get('encryptedData'))
    iv = str_escape(req_json.get('iv'))
    # pc = WXBizDataCrypt(AppID, session_key)
    # print(pc.decrypt(encryptedData, iv))

    # 通过openid查用户，如果查到，返回用户信息，如果没查到，将用户信息保存
    searchAppUser = AppUser.query.filter_by(openid=openid).all()
    print(searchAppUser)
    if len(searchAppUser)==0:
        appUser = AppUser(
            openid=openid,
            session_key=session_key,
            username=nickName,
            realname = nickName,
            avatar = avatarUrl
        )
        db.session.add(appUser)
        db.session.commit()

    info = dict()
    info["code"] = 200
    info["token"] = "dzzs"
    info["openid"] = openid
    info["nickName"] = nickName
    info["phone"] = "12323122321312"
    print(session_key)
    res = {
        "data": info
    }
    return jsonify(res)

